package Dao;

import util.DatabaseUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BasDao {
    private Connection conn= null;

    public BasDao(Connection conn){
        this.conn = conn;
    }
    /**
     * 增、删、改操作
     * @param sql
     *  sql语句
     * @param params
     *  参数数组
     * @return 执行结果
     */
    protected int executeUpdate(String sql,Object... params){
        int result = 0;
        PreparedStatement pstmt = null;
        try {
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i+1,params[i]);
            }
            result = pstmt.executeUpdate();
        }catch(SQLException e){
            e.printStackTrace();
        }finally {
            DatabaseUtil.closeAll(null,pstmt,null);
        }
        return result;
    }

    /***
     * 查询操作
     * @param sql
     *  sql 语句
     * @param params
     *  参数数组
     * @return  查询结果
     */

    protected ResultSet executeQuery(String sql, Object... params){
        ResultSet rs = null;
        PreparedStatement pstmt = null;
        try{
            pstmt = conn.prepareStatement(sql);
            if(params!=null){
                for (int i = 0; i < params.length; i++) {
                    pstmt.setObject(i+1,params[i]);
                }
            }
            rs = pstmt.executeQuery();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return rs;
    }
}
